/*
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *      
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *      
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */

package bgtp;

import java.util.*;
import java.lang.*;

public class Scaner
{
    private BGTPLog	log	    = null;
    private String	tokenString = null;
    private int		offset	    = 0;
    private int		begin	    = 0;
    private String	rToken	    = null;
    private String	terms	    = "()&|!=~ ";
    private int		state	    = 0;
    private final int	SCAN	    = 1;
    private final int	RET	    = 2;
    private final int	FIN	    = 3;
    private final int	ERR	    = 4;

    public Scaner()
    {
	log = new BGTPLog("Scaner");
    }

    public void setString(String test)
    {
	tokenString = test; 
	offset	    = 0;
	begin	    = 0;
    }

    public boolean isTerm(String tkn)
    {
	if(null == tkn)
	    {
		return true;
	    }

	if(terms.indexOf(tkn) >= 0)
	    {
		return true;
	    }
	return false;
    }

    public String getToken()
    {
	state  = SCAN;
	rToken = null;
	boolean nowfin = false;

	while(false == nowfin)
	    {
		switch(state)
		    {
		    case SCAN:
			//log.info("getToken", "SCAN");
			if(offset == tokenString.length())
			    {
				state = RET;
				if(offset == begin)
				    {
					state = FIN;
				    }
				break;
			    }

			if(terms.indexOf(tokenString.charAt(offset)) >= 0)
			    {
				state = RET;

				if(offset - begin >= 1)
				    {
					offset--;
				    }
			    }
			offset++;
			break;
			
		    case RET:
			rToken = tokenString.substring(begin, offset);
			state  = FIN;
			begin  = offset;
			break;

		    case FIN:
			//log.info("getToken", "FIN");
			nowfin = true;
			break;
			
		    case ERR:
			//log.info("getToken", "ERR");
			System.out.println("shit happens");
			state = FIN;
			break;
			
		    default:
			break;
		    }
	    }
	return rToken;
    }
}
